// 头像修改组件
Vue.component('profile-avatar', {
  props: ['avatarUrl'],
  data() {
    return {
      localAvatar: this.avatarUrl || '',
      uploading: false
    };
  },
  watch: {
    avatarUrl: {
      handler(newVal) {
        this.localAvatar = newVal || '';
      },
      immediate: true
    }
  },
  template: `
    <div>
      <div style="font-size: 22px; font-weight: bold; margin-bottom: 18px;">修改头像</div>
      <el-avatar :size="100" :src="localAvatar" icon="el-icon-user" style="font-size:36px"></el-avatar>
      <div style="margin-top:20px;">
        <el-upload
          action="#"
          :show-file-list="false"
          :http-request="handleAvatarUpload"
          :before-upload="beforeAvatarUpload"
          :disabled="uploading"
        >
          <el-button size="mini" type="primary" :loading="uploading">
            {{ uploading ? '上传中...' : '上传新头像' }}
          </el-button>
        </el-upload>
      </div>
    </div>
  `,
  methods: {
    async handleAvatarUpload(options) {
      this.uploading = true;
      try {
        const response = await uploadAPI.uploadAvatar(options.file);
        if (response.code === 200) {
          // 更新头像URL - 将反斜杠转换为正斜杠，并确保以/开头
          let avatarUrl = response.data.avatar_url.replace(/\\/g, '/');
          if (!avatarUrl.startsWith('/')) {
            avatarUrl = '/' + avatarUrl;
          }
          this.localAvatar = avatarUrl;
          
          // 更新localStorage中的用户信息
          const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
          userInfo.avatar = avatarUrl;
          localStorage.setItem('userInfo', JSON.stringify(userInfo));
          
          // 通知父组件头像已更新
          this.$emit('avatar-updated', avatarUrl);
          
          // 触发全局事件，通知导航栏更新头像
          this.$root.$emit('avatar-updated', avatarUrl);
          
          this.$message.success('头像上传成功');
        } else {
          this.$message.error(response.msg || '头像上传失败');
        }
      } catch (error) {
        console.error('头像上传失败:', error);
        this.$message.error(error.message || '头像上传失败');
      } finally {
        this.uploading = false;
      }
    },
    beforeAvatarUpload(file) {
      // 检查文件类型
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      
      // 检查文件大小 (5MB)
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!');
        return false;
      }
      
      return true;
    }
  }
});